package controllers

import (
	"github.com/astaxie/beego"
	"strings"
	"encoding/json"
	"mailsrv/models"
	"mailsrv/utils"
	"runtime"
)

var LoginSessName string = "USER_LOGIN_SESS"
var NoLoginController []string = []string{
	"PublicController",
	"ApiController",
	}

var SystemType string = runtime.GOOS

type BaseController struct {
	beego.Controller
	controllerName string             //当前控制名称
	actionName     string             //当前action名称
	sessUserInfo *models.AdminUser
}


type baseJsonResultFormat struct{
	Data interface{} `json:"data"`
	Info string `json:"info"`
	Status int `json:"status"`
}
type pageJsonResult struct {
	Code int `json:"code"`
	Msg string `json:"msg"`
	Count int64 `json:"count"`
	Data interface{} `json:"data"`
}





func (this *BaseController) Prepare() {
	beego.Notice("###STAR####")

	//附值
	this.controllerName, this.actionName = this.GetControllerAndAction()
	this.adapterUserInfo()

	isCheck := utils.StringInArray(this.controllerName, NoLoginController)
	if isCheck != true{
		beego.Notice("登录检测")
		this.checkLogin()
	}

	this.Data["static_js"] = "/static/js"
	this.Data["kit_admin"] = "/static/kit_admin"
	this.Data["site_name"] = "邮件微服务"
}




func (this *BaseController) Finish(){
	beego.Notice("###end###")
}


func (this *BaseController) SetUserLoginSess(user *models.AdminUser) error{
	this.SetSession(LoginSessName, user)
	return nil
}

func (this *BaseController) ClearUserLoginSess() error{
	this.DelSession(LoginSessName)
	return nil
}


/*
登录检测
 */
func (this *BaseController) checkLogin() {
	//登录页面地址
	urlstr := this.URLFor("PublicController.Login")


	if this.sessUserInfo == nil || this.sessUserInfo.Id == 0 {
		if this.Ctx.Input.IsAjax() {
			this.ajaxReturn(map[string]string{"url":urlstr}, "请登录", 400)
		}
		this.Redirect(urlstr, 302)
		this.StopRun()
	}else{
		beego.Notice(this.sessUserInfo)
	}
}

//从session里取用户信息写入base结构中
func (this *BaseController) adapterUserInfo() {
	session_info := this.GetSession(LoginSessName)
	if session_info != nil {
		this.sessUserInfo = session_info.(*models.AdminUser)
		this.Data["sess_user_info"] = session_info
	}
}


/*
*分页数据接口返回
 */
func (this *BaseController) pageApiJson(datas interface{}, total int64, msg string, code int){
	result := pageJsonResult{code, msg, total, datas}
	jsonencode,_:=json.Marshal(result)
	this.Ctx.Output.Header("Content-Type","text/json;charset=utf-8")
	this.Ctx.ResponseWriter.Write(jsonencode)
	this.StopRun()
}

func (this *BaseController) toJson(data interface{}){
	jsonencode,_:=json.Marshal(data)
	this.Ctx.Output.Header("Content-Type","text/json;charset=utf-8")
	this.Ctx.ResponseWriter.Write(jsonencode)
	this.StopRun()
}


func (this *BaseController) ajaxReturn(data interface{}, info string, status int) {
	result := baseJsonResultFormat{data, info, status}
	this.Data["json"] = result
	this.ServeJSON()
	this.StopRun()
}


// 重定向 去错误页
func (this *BaseController) goError(msg string) {
	isajax := this.Ctx.Input.IsAjax()
	if isajax{
		this.ajaxReturn("", msg, 400)
	}else{
		//还不支持直接渲染错误页面，只能重定向到新的错误页面
		errorurl := this.URLFor("PublicController.AbortPage")
		this.SetSession("TOP_ABORT_MSG", msg)
		this.Redirect(errorurl, 302)
		this.StopRun()
	}
}


// 第一个参数模板，第二个参数为layout
func (this *BaseController) setTpl(template ...string) {

	var tplName, layout string
	layout = "layout/layout_admin.html"
	switch {
	case len(template) == 1:
		tplName = template[0]
	case len(template) == 2:
		tplName = template[0]
		layout = template[1]
		this.Layout = layout
	default:
		//不要Controller这个10个字母
		ctrlName := strings.ToLower(this.controllerName[0 : len(this.controllerName)-10])
		actionName := strings.ToLower(this.actionName)
		tplName = ctrlName + "/" + actionName + ".html"
	}

	this.TplName = tplName
}